<template>
  <com-el-dialog-ex
    title="创建用户"
    v-model:visible="visible"
    @open="resetForm"
    @confirm="submitForm"
    @cancel="closed"
  >
    <el-form ref="ruleFormRef" label-width="auto" size="default" :model="ruleForm" :rules="rules">
      <el-form-item prop="loginId" label="用户名：">
        <el-input v-model="ruleForm.loginId" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item prop="realName" label="真实姓名：">
        <el-input v-model="ruleForm.realName" placeholder="请输入真实姓名" />
      </el-form-item>
      <el-form-item prop="password" label="密码：">
        <el-input
          show-password
          clearable
          type="password"
          prefix-icon="Lock"
          placeholder="请输入新密码"
          v-model="ruleForm.password"
        />
      </el-form-item>
    </el-form>
  </com-el-dialog-ex>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { defaultAddForm, type AddForm, addFormRule } from '@/common/model/user/addForm'
import ComElDialogEx from '@/components/com-el-dialog-ex/com-el-dialog-ex.vue'

defineOptions({
  name: 'AddView',
})

//region # 属性

// 应用实例
const { proxy }: any = getCurrentInstance()

// 显示状态
const visible = defineModel('visible', {
  type: Boolean,
  required: true,
  default: false,
})

// 表单
const ruleFormRef = ref<FormInstance>()

// 验证表单
let ruleForm = reactive<AddForm>(defaultAddForm)

// 验证规则
const rules = reactive<FormRules<AddForm>>(addFormRule)

// 组件事件列表
const emits = defineEmits(['closed'])

//endregion

//region # Hooks

//endregion

//region # 方法

// Action

/**
 * 提交
 * */
const submitForm = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      //创建用户
      await proxy.$api.user.createUser(ruleForm.loginId, ruleForm.realName, ruleForm.password)
      proxy.$service.toast.success('创建用户成功！')
      tryClose(true)
    }
  })
}

/**
 * 重置表单
 * */
const resetForm = () => {
  if (!ruleFormRef.value) return

  ruleForm = Object.assign(ruleForm, defaultAddForm)
  ruleFormRef.value.resetFields()
}

/**
 * 重置表单
 * */
const closed = () => {
  tryClose(false)
}

/**
 * 尝试关闭
 * @param result - 结果
 * */
const tryClose = (result: boolean) => {
  visible.value = false
  emits('closed', result)
}

//endregion

//region # 事件

/**
 * 加载完毕
 * */
onMounted(async () => {})
//endregion
</script>

<style scoped>
@import 'AddView.less';
</style>
